package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @author SunSun
 * @date 2021/10/25
 */
@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Override
    public String  publish(Movement movement) {
        try {
            movement.setPid(idWorker.getNextId("movement"));

            movement.setCreated(System.currentTimeMillis());

            mongoTemplate.save(movement);


            timeLineService.savetimeLine(movement.getUserId(),movement.getId());
        } catch (Exception e) {
            //忽略事务处理
            e.printStackTrace();
        }
        return movement.getId().toHexString();
    }

    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {

        Criteria criteria=Criteria.where("userId").is(userId).and("state").is(1);

        Query query=Query.query(criteria).skip((page-1)*pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        List<Movement> movements = mongoTemplate.find(query, Movement.class);

        return new PageResult(page,pagesize,0l,movements);
    }

    @Override
    public List<Movement> findFriendMovement(Long userId, Integer page, Integer pagesize) {
        Criteria criteria=Criteria.where("friendId").is(userId);
        Query query=Query.query(criteria).skip((page-1)*pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);

        List<ObjectId> movementId = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);

        Query query1=Query.query(Criteria.where("id").in(movementId).and("state").is(1));

        List<Movement> ts = mongoTemplate.find(query1, Movement.class);

        return ts;
    }

    @Override
    public List<Movement> randomMovements(Integer pagesize) {
        TypedAggregation<Movement> movementTypedAggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(pagesize));
        AggregationResults<Movement> aggregate = mongoTemplate.aggregate(movementTypedAggregation, Movement.class);
        return aggregate.getMappedResults();
    }

    @Override
    public List<Movement> findMovementsByPids(List<Long> pids) {
        Criteria criteria=Criteria.where("pid").in(pids);
        Query query=Query.query(criteria);
        return mongoTemplate.find(query,Movement.class);
    }

    @Override
    public Movement findOne(String movementID) {
        return mongoTemplate.findById(movementID,Movement.class);
    }

    @Override
    public PageResult findByUserId(Integer page, Integer pagesize, Long uid, Integer states) {
        Query query=new Query();
        if (uid!=null){
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if(states!=null){
            query.addCriteria(Criteria.where("state").is(states));
        }
        long count = mongoTemplate.count(query, Movement.class);
        query.skip((page-1)*pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));

        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,count,list);
    }

    @Override
    public void update(String movementId, int state) {
        Query query= Query.query(Criteria.where("Id").is(movementId));
        Update update=Update.update("state",state);
        mongoTemplate.findAndModify(query,update,Movement.class);
    }
}
